package io.xccit.dao.impl;

import io.xccit.dao.UserDao;
import io.xccit.pojo.User;
import io.xccit.util.DBUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author CH_ywx
 * @date 2023/9/30
 * @description 用户dao层
 */
public class UserDaoImpl implements UserDao {

    private QueryRunner runner = new QueryRunner(DBUtil.getDataSource());
    private Connection connection = DBUtil.getConnection();

    /**
     * 检查账号可用性
     *
     * @param user
     * @return
     */
    @Override
    public User checkUser(User user) {
        User u = null;
        String username = user.getUsername();
        String sql = "select * from tb_user where username=?";
        ResultSetHandler userHandler = new BeanHandler(User.class);
        try {
            u = (User)runner.query(connection, sql, userHandler, new Object[]{username});
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return u;
    }

    /**
     * 用户登录
     *
     * @param user 参数
     * @return
     */
    @Override
    public User login(User user) {
        if (connection == null){
            connection = DBUtil.getConnection();
        }
        User u = null;
        String username = user.getUsername();
        String password = user.getPassword();
        String sql = "select * from tb_user where username=? and password=?";
        ResultSetHandler userHandler = new BeanHandler(User.class);
        try {
            u = (User)runner.query(connection, sql, userHandler, new Object[]{username, password});
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return u;
    }

    /**
     * 用户注册
     *
     * @param user
     * @return
     */
    @Override
    public int register(User user) {
        if (connection == null){
            connection = DBUtil.getConnection();
        }
        String username = user.getUsername();
        String password = user.getPassword();
        String nickname = user.getNickname();
        String sql = "insert into tb_user(username,password,nickname) values(?,?,?)";
        ResultSetHandler<User> handler = new BeanHandler<>(User.class);
        int rows = 0;
        try {
            User insert = runner.insert(connection,sql, handler, new Object[]{username, password, nickname});
            if (insert != null){
                rows = 1;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return rows;
    }
}
